package 自定义注解实现数据验证;

import java.lang.annotation.*;
import java.lang.reflect.Field;

// 自定义注解：字段长度验证
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Length {
    int min() default 0;
    int max() default Integer.MAX_VALUE;
    String message() default "字段长度不符合要求";
}

// 自定义注解：非空验证
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface NotEmpty {
    String message() default "字段不能为空";
}

// 用户类使用注解
class User {
    @NotEmpty(message = "用户名不能为空")
    private String username;
    
    @Length(min = 6, max = 20, message = "密码长度必须在6-20之间")
    private String password;
    
    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
}

// 验证工具类
class Validator {
    public static void validate(Object obj) throws IllegalAccessException, IllegalArgumentException {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        
        for (Field field : fields) {
            field.setAccessible(true);
            
            // 检查NotEmpty注解
            if (field.isAnnotationPresent(NotEmpty.class)) {
                NotEmpty notEmpty = field.getAnnotation(NotEmpty.class);
                Object value = field.get(obj);
                if (value == null || value.toString().trim().isEmpty()) {
                    throw new IllegalArgumentException(notEmpty.message());
                }
            }
            
            // 检查Length注解
            if (field.isAnnotationPresent(Length.class)) {
                Length length = field.getAnnotation(Length.class);
                Object value = field.get(obj);
                if (value != null) {
                    int len = value.toString().length();
                    if (len < length.min() || len > length.max()) {
                        throw new IllegalArgumentException(length.message());
                    }
                }
            }
        }
    }
}

public class AnnotationDemo1 {
    public static void main(String[] args) {
        User user1 = new User("admin", "123456");
        User user2 = new User("", "123");
        
        try {
            Validator.validate(user1);
            System.out.println("user1 验证通过");
            
            Validator.validate(user2); // 这里会抛出异常
        } catch (Exception e) {
            System.out.println("验证失败: " + e.getMessage());
        }
    }
}